package com.wy.util.security;

import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wy.entity.User;
import com.wy.util.Constant;

/**
 * 验证用户cookie
 * @author WY
 *
 */
public final class CookieUtil {
	
	/**
	 * 验证cookie
	 * @param c 传入的Class对象
	 * @param params cookie的key集合
	 * @return Class<T>的实例
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> T validate(Class<T> c,Set<String> params,HttpServletRequest request) throws InstantiationException, IllegalAccessException{
		T t = c.newInstance();
		
		return t;
	}
	
	/**
	 * 验证用户Cookie
	 * @param request
	 * @return User对象
	 */
	public static User validataUser(HttpServletRequest request){
		User user = new User();
		boolean flag1 = false;
		boolean flag2 = false;
		Cookie[] cookies = request.getCookies();
		if(cookies != null && cookies.length > 0){
			for(Cookie c :cookies){
//				System.out.println(c.getName() +"-->"+ c.getValue());
				if(c.getName().equals(Constant.USER_COOKIE_USERNAME)){
					user.setUsername(c.getValue());
					flag1 = true;
				}
				if(c.getName().equals(Constant.USER_COOKIE_PASSWORD)){
					user.setPassword(c.getValue());
					flag2 =true;
				}
			}
		}
		if(flag1 && flag2){
			return user;
		}
		return null;
	}
	
	/**
	 * 操作User登录信息Cookie
	 * @param response
	 * @param maxAge cookie保存时间，为0则删除cookie
	 */
	public static void operateUserCookie(HttpServletResponse response, User user, int maxAge){
		String username = null;
		String password = null;
		if(user != null){
			username = user.getUsername();
			password = user.getPassword();
		}
		Cookie c_username = new Cookie(Constant.USER_COOKIE_USERNAME, username);
		Cookie c_password = new Cookie(Constant.USER_COOKIE_PASSWORD, password);
		c_username.setMaxAge(maxAge);
		c_password.setMaxAge(maxAge);
		response.addCookie(c_username);
		response.addCookie(c_password);
	}
}
